﻿using Microsoft.AspNetCore.Http;
using Newtonsoft.Json;
using System.IO;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;

namespace Xman.Extensions.Http
{
    public static class HttpRequestExtensions
    {
        public static async Task<T> RequestTo<T>(this HttpRequest request) where T : class
        {
            var body = await request.RequestToString();
            return JsonConvert.DeserializeObject<T>(body);
        }

        public static async Task<string> RequestToString(this HttpRequest request)
        {
            request.EnableBuffering();

            var body = "";
            var stream = request.Body;
            stream.Seek(0, SeekOrigin.Begin);
            using (var reader = new StreamReader(stream, Encoding.UTF8, true, 1024, true))
            {
                body = await reader.ReadToEndAsync();
            }
            stream.Seek(0, SeekOrigin.Begin);

            return body;
        }

        public static void Set(this HttpRequestHeaders headers, string name, string value)
        {
            if (headers.Contains(name))
            {
                headers.Remove(name);
            }
            headers.Add(name, value);
        }
    }
}
